import http from '@/utils/http'
import { packBom, Tree } from '@/views/TechniqueEditor/types/tree-type'

export const connectCreoson = async (): Promise<string> => {
  try {
    const rep = await http({
      method: 'post',
      url: '/creoson',
      data: {
        function: 'connect',
        command: 'connection',
      },
    })
    // console.log(rep.data.sessionId)
    return rep.data.sessionId
  } catch (error) {
    console.log('连接错误', error)
  }
}

export const getBom = async (sessionId: string, time: number = 1): Promise<Tree> => {
  if (time > 3) {
    throw new Error(`连接后端失败`)
  }
  time++
  const rep = await http({
    method: 'post',
    url: '/creoson',
    data: {
      function: 'get_paths',
      command: 'bom',
      sessionId: sessionId,
      data: {
        paths: true,
      },
    },
  })

  const { error } = rep.data.status
  if (error) {
    return getBom(sessionId, time)
  }

  const { file, children } = rep.data.data.children
  const packedBom = packBom(new Tree(file, children))
  return packedBom
}
